﻿/**********************************************************
 * 模    块	：	文件操作类
 * 作    者	：	Jasper
 * 编写时间	：	2010-04-24
 * 实现功能	：	
 * 详细描述	：	
 * *********************************************************/

namespace Basic4Net.Utility.IO
{
	using System.Text;
	using System.IO;
	using System.Collections;
	using System.Web;
	using System.Web.UI;

	/// <summary>
	/// FileTools 文件类工具
	/// </summary>
	public class FileTools
	{
		/// <summary>
		/// 创建文件
		/// </summary>
		/// <param name="path">文件路径</param>
		/// <param name="content">文件内容</param>
		public static void Create(string path, byte[] content)
		{
			FileTools.EnsurePath(Path.GetDirectoryName(path));
			FileStream stream1 = new FileStream(path, FileMode.OpenOrCreate);
			stream1.Write(content, 0, content.Length);
			stream1.Close();
		}

		/// <summary>
		/// 创建文件
		/// </summary>
		/// <param name="path">文件路径</param>
		/// <param name="content">文件内容</param>
		public static void Create(string path, string content)
		{
			FileTools.EnsurePath(Path.GetDirectoryName(path));
			FileStream stream1 = new FileStream(path, FileMode.OpenOrCreate);
			StreamWriter writer1 = new StreamWriter(stream1);
			writer1.WriteLine(content);
			writer1.Close();
			stream1.Close();
		}

		/// <summary>
		/// 创建文件
		/// </summary>
		/// <param name="path">文件路径</param>
		/// <param name="content">文件内容</param>
		/// <param name="encoding">内容编码</param>
		public static void Create(string path, string content, Encoding encoding)
		{
			FileTools.EnsurePath(Path.GetDirectoryName(path));
			FileStream stream1 = new FileStream(path, FileMode.OpenOrCreate);
			StreamWriter writer1 = new StreamWriter(stream1, encoding);
			writer1.WriteLine(content);
			writer1.Close();
			stream1.Close();
		}

		/// <summary>
		/// 在服务器创建文件
		/// </summary>
		/// <param name="Path">保存路径(example:C:\tempfile)</param>
		/// <param name="Context">文件内容</param>
		/// <param name="FileName">文件名(example:a.exe)</param>
		/// <returns></returns>
		public static string CreateTempFile(string Path, byte[] Context, string FileName)
		{
			if (!Directory.Exists(Path))
				Directory.CreateDirectory(Path);
			System.Threading.Thread.Sleep(10);
			string FullName = FileName;
			System.IO.FileStream fs = File.Create(Path + @"\" + FullName);
			fs.Write(Context, 0, Context.Length);
			fs.Flush();
			fs.Close();
			return FullName;
		}

		/// <summary>
		/// 新建或打开现有文件，并添加内容
		/// </summary>
		/// <param name="path">文件路径</param>
		/// <param name="content">文件内容</param>
		public static void CreateAppend(string path, string content)
		{
			FileTools.EnsurePath(Path.GetFullPath(path));
			FileStream stream1 = new FileStream(path, FileMode.Append, FileAccess.Write);
			StreamWriter writer1 = new StreamWriter(stream1);
			writer1.WriteLine(content);
			writer1.Close();
			stream1.Close();
		}

		/// <summary>
		/// 新建或打开现有文件，并添加内容
		/// </summary>
		/// <param name="path">文件路径</param>
		/// <param name="content">文件内容</param>
		/// <param name="encoding">内容编码</param>
		public static void CreateAppend(string path, string content, Encoding encoding)
		{
			FileTools.EnsurePath(Path.GetFullPath(path));
			FileStream stream1 = new FileStream(path, FileMode.Append, FileAccess.Write);
			StreamWriter writer1 = new StreamWriter(stream1, encoding);
			writer1.WriteLine(content);
			writer1.Close();
			stream1.Close();
		}

		/// <summary>
		/// 删除文件
		/// </summary>
		/// <param name="path">文件路径</param>
		public static void Delete(string path)
		{
			File.Delete(path);
		}

		/// <summary>
		/// 判断路径是否存在，如果不存在则创建该路径目录结构
		/// </summary>
		/// <param name="path">路径</param>
		private static void EnsurePath(string path)
		{
			if (!Directory.Exists(path))
			{
				Directory.CreateDirectory(path);
			}
		}

		/// <summary>
		/// 判断文件是否存在
		/// </summary>
		/// <param name="path">文件路径</param>
		/// <returns></returns>
		public static bool Exists(string path)
		{
			return File.Exists(path);
		}

		/// <summary>
		/// 读取指定文件的内容
		/// </summary>
		/// <param name="path">文件路径</param>
		/// <returns>按行排列文本内容</returns>
		public static string[] Read(string path)
		{
			string text1;
			ArrayList list1 = new ArrayList();
			FileStream stream1 = new FileStream(path, FileMode.Open);
			StreamReader reader1 = new StreamReader(stream1);
			while ((text1 = reader1.ReadLine()) != null)
			{
				list1.Add(text1);
			}
			reader1.Close();
			stream1.Close();
			return (string[])list1.ToArray(typeof(string));
		}

		/// <summary>
		/// 输出二进制附件内容_默认为下载
		/// </summary>
		/// <param name="rs">HttpResponse对象</param>
		/// <param name="attach">附件内容</param>
		/// <param name="title">文件名</param>
		/// <param name="extname">扩展名</param>
		/// <param name="fsize">文件大小</param>
		public static void ResponseAttach(HttpResponse rs, byte[] attach, string title,
			string extname, int fsize)
		{
			rs.ContentType = "application/octet-stream";
			rs.AddHeader("Content-Disposition", "attachment;FileName=" + HttpUtility.UrlEncode(title, System.Text.Encoding.Default) + "." + extname);
			rs.OutputStream.Write(attach, 0, fsize);
			rs.End();
		}

		/// <summary>
		/// 输出二进制附件内容_默认为下载
		/// </summary>
		/// <param name="rs">HttpResponse对象</param>
		/// <param name="attach">附件内容</param>
		/// <param name="fileName">完整文件名</param>
		public static void ResponseAttach(HttpResponse rs, byte[] attach, string fileName)
		{
            rs.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            rs.Charset = "Unicode";
			rs.ContentType = "application/octet-stream";
            rs.AddHeader("Content-Disposition", "attachment;FileName=" + HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8) );
			rs.OutputStream.Write(attach, 0, attach.Length);
			rs.End();
		}

		/// <summary>
		/// DownLoad File to Client
		/// </summary>
		/// <param name="FileName"></param>
		/// <param name="Context"></param>
		/// <param name="page"></param>
		public static void DownLoadFile(string FileName, byte[] Context, Page page)
		{
			page.Response.ContentType = "application/octet-stream";
			if (FileName == "") FileName = "Temp";
			page.Response.AddHeader("Content-Disposition", "attachment;FileName=" + FileName);
			if (Context != null && Context.Length > 0)
				page.Response.BinaryWrite(Context);
			else
				page.Response.BinaryWrite(new byte[1]);
			page.Response.End();
		}

		/// <summary>
		/// 上传二进制附件内容
		/// </summary>
		/// <param name="uploadFile">客户端文件</param>
		/// <param name="attach">保存文件的数组</param>
		///<param name="fullName">文件名</param>
		/// <param name="extendName">文件扩展名</param>
		/// <param name="fSize">文件大小</param>
		public static void UploadAttach(HttpPostedFile uploadFile, ref byte[] attach, ref string fullName,
			ref string extendName, ref float fSize)
		{
			if (uploadFile.ContentLength > 0)
			{
				string nam = uploadFile.FileName;
				//获取文件名(抱括路径)
				int n = nam.LastIndexOf(@"\");
				int i = nam.LastIndexOf(".");
				//获取文件名
				fullName = nam.Substring(n + 1);
				//获取文件扩展名
				if (i > 0)
				{
					extendName = nam.Substring(i + 1);
				}
				else
				{
					extendName = "";
				}
				//获取文件大小
				fSize = uploadFile.ContentLength;

				//获取二进制文件
				attach = new byte[uploadFile.ContentLength];
				Stream StreamObject = uploadFile.InputStream;
				StreamObject.Read(attach, 0, uploadFile.ContentLength);
			}
		}


		/// <summary>
		/// 根据文件物理路径获取二进制数据
		/// </summary>
		/// <param name="uploadFile">HttpPostedFile对象</param>
		/// <returns></returns>
		public static byte[] GetAttach(HttpPostedFile uploadFile)
		{
			byte[] attach = new byte[uploadFile.ContentLength];
			if (uploadFile.ContentLength > 0)
			{
				uploadFile.InputStream.Read(attach, 0, uploadFile.ContentLength);
			}
			return attach;
		}

		/// <summary>
		/// 获取文件名
		/// </summary>
		/// <param name="FileFullName">文件名带路径</param>
		/// <returns></returns>
		public static string GetFileName(string FileFullName)
		{
			return FileFullName.Substring(FileFullName.LastIndexOf('\\'), FileFullName.Length - FileFullName.LastIndexOf('\\')).Trim('\\');
		}
		/// <summary>
		/// 获取文件全名
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
		public static string GetFullFileName(string path)
		{
			if (!File.Exists(path)) return "";

			return path.Substring(path.LastIndexOf('\\'), path.Length - path.LastIndexOf('\\')).Trim('\\');
		}

		/// <summary>
		/// 获取扩展名
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
		public static string GetExtension(string path)
		{
			return path.Substring(path.LastIndexOf('.'), path.Length - path.LastIndexOf('.')).Trim('.');
		}
	}
}
